package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.Employee;
import com.example.demo.entity.User;
import com.example.demo.mapper.EmployeeMapper;
import com.example.demo.service.EmployeeService;
import com.example.demo.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
@RequestMapping()
public class LoginController {
    @Resource
    EmployeeService employeeService;

    @Resource
    UserService userService;

    @PostMapping("/employee/login")
    public Result<?> employeeLoogin(@RequestBody Employee employee){
        String username=employee.getUsername();
        Employee res=employeeService.loginEmployee(username);
        if(res == null) {
            return Result.error("-1", "账号不存在");
        }
        String password=employee.getPassword();
        if(!res.getPassword().equals(password)) {
            return Result.error("-1", "账号或密码错误");
        }
        return Result.success(res);
    }

    @PostMapping("/user/login")
    public Result<?> userLogin(@RequestBody User user){
        String username=user.getUsername();
        User res=userService.loginUser(username);
        if(res == null) {
            return Result.error("-1", "账号不存在");
        }
        String password=user.getPassword();
        if(!res.getPassword().equals(password)) {
            return Result.error("-1", "账号或密码错误");
        }
        return Result.success(res);
    }

    @PostMapping("/user/register")
    public Result<?> userRegister(@RequestBody User user){
        User res=userService.loginUser(user.getUsername());
        if(res == null) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
            Date date = new Date();
            user.setCreatedTime(formatter.format(date));
            user.setUpdatedTime(formatter.format(date));
            userService.insert(user);
            return Result.success();
        }else {
            return Result.error("-1", "用户名已存在");
        }
    }

}
